package com.gitee.huanminabc.jcommon.file;

import com.gitee.huanminabc.jcommon.exception.CommonException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 简要描述
 *
 * @Author: mac
 * @Date: 2025/4/3 13:45
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
@Slf4j
public class IoStreamUtil {



    /**
     * 把文件流转成字符串
     *
     * @param is
     * @return
     */
    public static String inputStreamToStr(InputStream is) {
        byte[] bytes = inputStreamToByte(is);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    // 文件流InputStream转byte
    // 文件流FileInputStream转byte
    //流由外部进行关闭
    public static byte[] inputStreamToByte(InputStream inputStream) {
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            int available = inputStream.available();
            byte[] buff = new byte[available]; //buff用于存放循环读取的临时数据
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, available)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            return swapStream.toByteArray();
        } catch (IOException e) {
            throw new CommonException(e);
        }
    }

    /*
       字符串转文件流
    */
    public static InputStream strToInputStream(String str) {
        return new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
    }


    // 字节转文件流
    public static InputStream byteToInputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }


    //将输入流转换为输出流
    public static void inputStreamToOutputStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    }

    //文件转换为InputStream
    public static InputStream fileToInputStream(File file) {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new CommonException(e);
        }
    }
}
